package com.netx.ebs;
import com.netx.data.DatabaseException;
import com.netx.data.NoSuchInstanceException;
import com.netx.data.ValueList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.netx.generics.util.Strings;
import com.netx.generics.basic.Checker;
import com.netx.generics.collections.ImmutableSet;
import com.netx.generics.sql.Row;
import com.netx.generics.sql.Table;


public class Permissions extends EbsEntity {

	public Permissions() {
	}

	public long add(String name) throws DatabaseException {
		ValueList values = new ValueList();
		values.addValue("name", name);
		return insert(values);
	}
	
	public void remove(long permissionID) throws DatabaseException {
		if(delete(permissionID) == 0) {
			throw new NoSuchInstanceException("permissionID: "+permissionID);
		}
		// update running sessions
		Iterator<Session> it = sManager.getAllSessions().iterator();
		while(it.hasNext()) {
			Session s = it.next();
			Permission[] perms = s.getUser().getPermissions();
			for(Permission p : perms) {
				// this user has the permission:
				if(p.getPrimaryKey() == permissionID) {
					// remove the permission from the array:
					Permission[] newPermissions = new Permission[perms.length-1];
					for(int i=0, j=0; i<perms.length; i++) {
						if(perms[i].getPrimaryKey() != permissionID) {
							newPermissions[j++] = perms[i];
						}
					}
					s.getUser().setPermissions(newPermissions);
					// TODO force the UI to be changed?
				}
			}
		}
	}
	
	public Permission find(long permissionID) throws DatabaseException {
		Row result = select("permission_id, name", permissionID);
		if(result == null) {
			return null;
		}
		else {
			return new Permission(result);
		}
	}
	
	public Permission find(String name) throws DatabaseException {
		Checker.checkEmpty(name, "name");
		Table result = getConnection().select("permission_id, name FROM permissions WHERE name=\""+Strings.addSlashes(name)+"\"");
		if(result.isEmpty()) {
			return null;
		}
		else {
			return new Permission(result.getRow(0));
		}
	}

	public ImmutableSet<Permission> getAll() throws DatabaseException {
		Table perms = getConnection().select("permission_id, name FROM permissions");
		Set<Permission> all = new HashSet<Permission>();
		for(int i=0; i<perms.getRowCount(); i++) {
			all.add(new Permission(perms.getRow(i)));
		}
		return new ImmutableSet<Permission>(all);
	}
}
